let config = require("./config");
let baseUrl = config.baseUrl;

function getUserEvents() {
  return new Promise(function (resolve, reject) {
    let token = readToken();
    let url = baseUrl + "/users/yashujs/events?access_token=" + token + "&limit=" + config.userEventsCount;
    http.get(url, {}, function (res, err) {
      if (err) {
        console.error(err);
        reject(err);
        return;
      }
      if (res.statusCode !== 200) {
        toastLog("getUserEvents error");
        reject("getUserEvents error");
      } else {
        let data = res.body.json();
        resolve(data);
      }
    });
  });
}
function getRepos() {
  return new Promise(function (resolve, reject) {
    let token = readToken();
    let url = baseUrl + "/user/repos?access_token=" + token + "&sort=updated&page=1&per_page=" + config.repoCount;

    http.get(url, {}, function (res, err) {
      if (err) {
        console.error(err);
        reject(err);
        return;
      }
      if (res.statusCode !== 200) {
        toastLog("getRepos error");
        reject("getRepos error");
      } else {
        let data = res.body.json();
        resolve(data);
      }
    });
  });
}
function forkRepo(url) {

  // 提取仓库名
  let repoName = url.split("/").pop();
  // 提取owner
  let owner = url.split("/").slice(-2, -1)[0];
  return new Promise(function (resolve, reject) {
    let token = readToken();
    let url = baseUrl + "/repos/" + owner + "/" + repoName + "/forks";
    http.postJson(url, { access_token: token }, function (res, err) {
      if (err) {
        console.error(err);
        reject(err);
        return;
      }
      if (res.statusCode !== 200) {
        toastLog("forkRepo error");
        reject("forkRepo error");
      } else {
        let data = res.body.json();
        resolve(data);
      }
    });
    toastLog("fork仓库, 命令已发出, 请稍后查阅仓库");
  });
}

function getTree(url, sha) {
  sha = sha || "master";
  // getTree url: https://gitee.com/yashujs/gitee-for-android

  let arr = url.split("/");
  // 提取仓库名
  let repoName = arr[arr.length - 1];
  // 提取owner
  let owner = arr[arr.length - 2];
  return new Promise(function (resolve, reject) {
    let token = readToken();
    let url = baseUrl + "/repos/" + owner + "/" + repoName + "/git/trees/" + sha + "?access_token=" + token;
    http.get(url, {}, function (res, err) {
      if (err) {
        console.error(err);
        reject(err);
        return;
      }
      if (res.statusCode !== 200) {
        toastLog("getTree error");
        reject("getTree error");
      } else {
        let data = res.body.json();
        resolve(data.tree);
      }
    });
  });
}
function getShaTree(url, sha) {
  sha = sha || "master";

  let urlWithoutBaseUrl = url.replace(baseUrl, "");
  let arr = urlWithoutBaseUrl.split("/");
  // 提取仓库名
  let repoName = arr[3];
  // 提取owner
  let owner = arr[2];
  return new Promise(function (resolve, reject) {
    let token = readToken();
    let url = baseUrl + "/repos/" + owner + "/" + repoName + "/git/trees/" + sha + "?access_token=" + token;
    http.get(url, {}, function (res, err) {
      if (err) {
        console.error(err);
        reject(err);
        return;
      }
      if (res.statusCode !== 200) {
        toastLog("getShaTree error");
        reject("getShaTree error");
      } else {
        let data = res.body.json();
        resolve(data.tree);
      }
    });
  });
}

function getBlob(url, sha, filepath) {
  let token = readToken();
  let urlWithoutBaseUrl = url.replace(baseUrl, "");
  let arr = urlWithoutBaseUrl.split("/");
  // 提取仓库名
  let repoName = arr[3];
  // 提取owner
  let owner = arr[2];
  return new Promise(function (resolve, reject) {
    let url = baseUrl + "/repos/" + owner + "/" + repoName + "/git/blobs/" + sha + "?access_token=" + token;

    http.get(url, {}, function (res, err) {
      if (err) {
        console.error(err);
        reject(err);
        return;
      }
      if (res.statusCode !== 200) {
        toastLog("getBlob error");
        reject("getBlob error");
      } else {
        let data = res.body.json();
        let content = data.content;
        let encoding = data.encoding;
        if (encoding === "base64") {
          var bytes = android.util.Base64.decode(content, 0);
          filepath = files.join(files.getSdcardPath(), config.dir, repoName, filepath);
          files.createWithDirs(filepath);
          files.writeBytes(filepath, bytes);
          resolve(filepath);
        } else {
          toastLog("未知 encoding");
        }
      }
    });
  });
}
// 加密token
function encryptToken(token) {
  let key = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
  let keyLen = key.length;
  let tokenLen = token.length;
  let result = "";
  for (let i = 0; i < tokenLen; i++) {
    let index = key.indexOf(token[i]);
    if (index === -1) {
      result += token[i];
    } else {
      result += key[index + 1];
    }
  }
  return result;
}
function decryptToken(token) {
  let key = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
  let keyLen = key.length;
  let tokenLen = token.length;
  let result = "";
  for (let i = 0; i < tokenLen; i++) {
    let index = key.indexOf(token[i]);
    if (index === -1) {
      result += token[i];
    } else {
      result += key[index - 1];
    }
  }
  return result;
}
function readToken() {
  let token = config.storage.get("公众号: 牙叔教程", false);
  if (token) {
    return decryptToken(token);
  }
  return "";
}
function writeToken(token) {
  let ciphertext = encryptToken(token);
  config.storage.put("公众号: 牙叔教程", ciphertext);
}
module.exports = {
  getUserEvents: getUserEvents,
  getRepos: getRepos,
  forkRepo: forkRepo,
  getTree: getTree,
  getBlob: getBlob,
  getShaTree: getShaTree,
  encryptToken: encryptToken,
  decryptToken: decryptToken,
  readToken: readToken,
  writeToken: writeToken,
};
